package com.oj.friend.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oj.common.core.constants.JwtConstants;
import com.oj.common.core.domain.TableDataInfo;
import com.oj.common.core.enums.ExamListType;
import com.oj.common.core.enums.ResultCode;
import com.oj.common.core.utils.JwtUtils;
import com.oj.common.core.utils.ThreadLocalUtil;
import com.oj.common.redis.service.RedisService;
import com.oj.common.security.exception.ServiceExpection;
import com.oj.common.security.service.TokenService;
import com.oj.friend.domain.exam.Exam;
import com.oj.friend.domain.exam.dto.ExamQueryDTO;
import com.oj.friend.domain.exam.vo.ExamVO;
import com.oj.friend.domain.user.UserExam;
import com.oj.friend.manager.ExamCacheManager;
import com.oj.friend.mapper.ExamMapper;
import com.oj.friend.mapper.UserExamMapper;
import com.oj.friend.service.IUserExamService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author bin
 * @Date 2025/6/4
 */
@Service
public class UserExamServiceImpl implements IUserExamService {

    @Resource
    private UserExamMapper userExamMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private ExamCacheManager examCacheManager;

    @Override
    public int enter(String token, Long examId) {
        //不用担心userId为空 因为filter已经取过一遍了 优化userId的获取方式
        Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID, Long.class);
        //1. 竞赛是否存在
        Exam exam = getExam(examId);
        //2. 是否已经开赛或结束
        checkExam(exam);
        //3. 是否已经报名过
        Long aLong = userExamMapper.selectCount(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examId)
        );
        if (aLong > 0) {
            // 已经报名过了
            throw new ServiceExpection(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId, examId);
        //4. 验证通过 添加用户-竞赛关系
        UserExam userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID, Long.class);
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        List<ExamVO> examVOList = new ArrayList<>();
        if (total == null || total <= 0L) {
            //从数据库中查询
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(examQueryDTO.getType(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO);
            if (CollectionUtil.isEmpty(examVOList)){
                return TableDataInfo.empty();
            }
            total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        return TableDataInfo.success(examVOList, total);
    }


    private static void checkExam(Exam exam) {
        // 判断竞赛是否开始
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            // 竞赛已经开始了
            throw new ServiceExpection(ResultCode.EXAM_CANNOT_OPERATE);
        } else if (exam.getEndTime().isBefore(LocalDateTime.now())) {
            // 竞赛已经结束了
            throw new ServiceExpection(ResultCode.EXAM_CANNOT_OPERATE);
        }
    }

    private Exam getExam(Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceExpection(ResultCode.EXAM_NOT_EXISTS);
        }
        return exam;
    }
}
